#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "png.h"

int main(int argc ,char **argv)
{
	unsigned char header[8];
	size_t bytesRead;
	int result = 0; FILE* fp = NULL; png_structp png_ptr = NULL; png_infop info_ptr = NULL;
	int color_type, bit_depth; png_uint_32 width; png_uint_32 height; png_byte channels;

	if (argc !=2 )
	{
		printf("eg:./pnginfo png_name\n");
		return -1;
	}
	fp = fopen(argv[1], "rb");
	if (fp == NULL)
	{
		result = -1;
		goto exit;
	}
	bytesRead = fread(header, 1, sizeof(header), fp);
	if (bytesRead != sizeof(header))
	{
		result = -2;
		goto exit;
	}
	if (png_sig_cmp(header, 0, sizeof(header)))
	{
		result = -3;
		goto exit;
	}
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png_ptr)
	{
		result = -4;
		goto exit;
	}
	info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
	{
		result = -5;
		goto exit;
	}
	if (setjmp(png_jmpbuf(png_ptr)))
	{
		result = -6;
		goto exit;
	}
	png_init_io(png_ptr, fp);
	png_set_sig_bytes(png_ptr, sizeof(header));
	png_read_info(png_ptr, info_ptr);
	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL);
	channels = png_get_channels(png_ptr, info_ptr);
	printf("pnginfo bit_depth:%d, channels:%d, color_type:%d\n", bit_depth, channels, color_type);

exit:
	if (fp != NULL)
	{
		fclose(fp);
		fp = NULL;
	}
	printf("pnginfo result:%d\n", result);
	return result;
}